import { deconstructionFn, importFromOrigin, splitMethods } from './common.js'

export const formatWatchItem = (str) => {
  const isFnFormat = str.search(/handler/g) >= 0
  if (isFnFormat) {
    const name = str.replace(/^(\w+):\s*?\{([\s\S]*?)\s*?\}$/, '$1')
    const body = str.replace(/^(\w+):\s*?\{([\s\S]*?)\s*?\}$/, '$2')
    const formattedBody = splitMethods(body)
    const handler = formattedBody.find((item) => item.search(/handler/) >= 0)
    const immediateOrDeep = formattedBody.find((item) => item.search(/(immediate|deep)/) >= 0)
    if (deconstructionFn(handler, 'watch')) {
      const { params, body, isAsync } = deconstructionFn(handler, 'watch')
      return `watch(()=>${name}.value,${isAsync ? 'async ' : ''}(${params})=>{${body}
              },{${immediateOrDeep || ''}})
          `
    } else {
      return ''
    }
  } else {
    if (deconstructionFn(str, 'watch')) {
      const { name, params, body, isAsync } = deconstructionFn(str, 'watch')
      return `watch(()=>${name}.value,${isAsync ? 'async ' : ''}(${params})=>{${body}
              })
          `
    }
  }
}
export const formatWatch = (str) => {
  if (!str) return ''
  const formattedStr = str.replace(/watch:\s?\{/g, '').replace(/\}$/g, '')
  const watchList = splitMethods(formattedStr)
  if (watchList.length > 0) {
    importFromOrigin('watch')
  }
  return watchList.map((item) => formatWatchItem(item.trim())).join('')
}
